//
//  NoteCell.m
//  WOPrototype
//
//  Created by Olof Millberg on 2010-04-16.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "NoteCell.h"

@implementation NoteCell
//@synthesize active;
@synthesize textView;
@synthesize postButton;
@synthesize backgroundField;
@synthesize delegate;

/*******************************************************************
 * Adjusts the size of the cell based on the size of the text view *
 *******************************************************************/
- (void) adjustSizeAnimated:(BOOL)isAnimated
{
	if (isAnimated)
	{
		[UIView beginAnimations:nil context:nil];
	}
	
	postButton.hidden = ![textView hasText];
	
	// Resize text view background (currently a UIButton)
	CGRect newFrame = self.backgroundField.frame;
	newFrame.size.height = textView.frame.size.height;
	self.backgroundField.frame = newFrame;
	
	// Reposition post button
	newFrame = self.postButton.frame;
	newFrame.origin.y = self.textView.frame.origin.y + self.textView.frame.size.height + 4;
	self.postButton.frame = newFrame;
	
	// Resize frame
	newFrame = self.frame;
	newFrame.size.height = backgroundField.frame.size.height;
	if (!postButton.hidden)
		newFrame.size.height += postButton.frame.size.height + 8;
	self.frame = newFrame;
	
	// Update height value (the history table viewcontroller should be observing this)
	if (cellHeight != self.frame.size.height)
	{
		cellHeight = self.frame.size.height;
		[delegate noteCell:self didChangeHeight:cellHeight];
	}
	
	if (isAnimated)
	{
		[UIView commitAnimations];
	}
}

/******************************************************
 * Not used atm. Called when the text view gets focus *
 ******************************************************/
- (void)textViewDidBeginEditing:(UITextView *)aTextView
{
	//[self setActive:YES animated:YES];
}

- (void)textViewDidEndEditing:(UITextView *)aTextView
{
	[self setActive:NO animated:YES];
}

/************************************************
 *  Called every time the user inputs something *
 ************************************************/
- (void)textViewDidChange:(UITextView *)aTextView
{	
	[self adjustSizeAnimated:YES];
}

/***********************************************
 * Not sure if this is going to be used either *
 ***********************************************/
- (void) setActive:(BOOL)isActive animated:(BOOL)isAnimated
{
	active = isActive;
	
	if (!active)
	{
		CGRect newFrame = self.textView.frame;
		// Make the text view as small as possible
		if ([self.textView hasText])
			newFrame.size.height = MIN(142, MAX(self.textView.contentSize.height, 61));
		else
			newFrame.size.height = 37;
		self.textView.frame = newFrame;
	}
	
	[self adjustSizeAnimated:isAnimated];
}

@end
